﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using ThinkDotNetBotApiCommon;

namespace ThinkDotNetEngine.Bots.Loaders
{
    public class AssemblyBotLoader:IBotLoader
    {
        public IEnumerable<BotBase> GetAllBots()
        {       
            var allbotAssemblies = GetBotAssemblies();

            foreach (Assembly botAssembly in allbotAssemblies)
            {
                Type[] botTypes = botAssembly.GetTypes().Where(t => t.BaseType == typeof (BotBase)).ToArray();
                if (botTypes.Length != 0)
                {
                    Type botToCreateType = botTypes[0];
                    var bot = (BotBase)botAssembly.CreateInstance(botToCreateType.FullName,
                                                                   true, BindingFlags.Default, null,
                                                                   new object[] {new BotController()},
                                                                   null, null);

                    yield return bot;
                }
            }
        }
        private IEnumerable<Assembly> GetBotAssemblies()
        {
            const string botsDirectoryName = "Bots";

            if (Directory.Exists(botsDirectoryName))
            {
                string[] botFiles = Directory.GetFiles(botsDirectoryName);

                foreach (var botFile in botFiles)
                {
                    var assembly = Assembly.LoadFrom(botFile);
                    yield return assembly;
                }
            }
        }
    }
}
